package com.sunyur.tailor.channel.web.outer.currency.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.base.ValidList;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.service.inner.currency.param.BatchSyncCurrencyParam;
import com.sunyur.tailor.channel.service.inner.currency.service.SunyurCurrencyService;
import com.sunyur.tailor.channel.web.outer.currency.dto.BatchSyncCurrencyDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author pengbing
 * @Description 公司主体控制层
 * @Date 15:45 2021/6/1
 * @Param
 * @return
 **/
@Slf4j
@RestController
@RequestMapping("/outer/currency")
public class CurrencyController {

    /**
     * 汇率服务接口
     */
    @Autowired
    private SunyurCurrencyService sunyurCurrencyService;

    /**
     * 批量同步汇率
     */
    @PostMapping(value = "/batchSync", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChannelResult<Boolean> batchSync(@RequestBody @Valid ValidList<BatchSyncCurrencyDTO> batchSyncCurrencyDTO) {
        log.info("CurrencyController batchSync param:{}", JSON.toJSONString(batchSyncCurrencyDTO));
        ChannelResult<Boolean> result = new ChannelResult<>();
        try {
            List<BatchSyncCurrencyParam> batchSyncCurrencyParam = batchSyncCurrencyDTO
                    .stream()
                    .map((BatchSyncCurrencyDTO batchSyncCurrency) -> BeanUtil.toBean(batchSyncCurrency, BatchSyncCurrencyParam.class))
                    .collect(Collectors.toList());
            result = sunyurCurrencyService.batchSyncCurrency(batchSyncCurrencyParam);
        } catch (Exception e) {
            log.error("CurrencyController batchSync exception:{}", e);
            result.setError(MiddleResultEnum.EXCEPTION.getCode(), MiddleResultEnum.EXCEPTION.getValue());
        }
        log.info("CurrencyController batchSync return:{}", JSON.toJSONString(result));
        return result;
    }
}
